<template>
  <div class="material-management-page">
    <div class="page-header">
      <h2 class="page-title">课程资料管理</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="openAddMaterialDialog">
          <i class="el-icon-plus"></i> 新增资料
        </el-button>
      </div>
    </div>

    <div class="chapter-selector">
      <el-form :model="chapterForm" label-width="80px">
        <el-form-item label="选择章节">
          <el-select v-model="selectedChapterID" placeholder="请先选择章节" style="width: 300px" @change="fetchMaterials">
            <el-option v-for="chapter in chapterList" :key="chapter.chapterID" :label="getChapterPath(chapter)" :value="chapter.chapterID" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="material-list-container">
      <div v-if="!selectedChapterID" class="empty-tip">请先选择章节</div>
      <div v-else-if="materialList.length === 0" class="empty-tip">该章节暂无课程资料</div>
      <el-table
          v-else
          :data="materialList"
          stripe
          border
          class="material-table">
        <el-table-column prop="materialID" label="资料ID" width="80"></el-table-column>
        <el-table-column prop="type" label="资料类型" width="100">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="filePath" label="资料路径" width="300">
          <template #default="scope">
            <el-link :href="scope.row.filePath" type="primary" :underline="false" @click.prevent="handleViewFile(scope.row)">
              {{ getFileName(scope.row.filePath) }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
                size="small"
                @click="openEditMaterialDialog(scope.row)">
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDeleteMaterial(scope.row.materialID)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑资料对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="500px"
        @open="onDialogOpen"
        @close="onDialogClose"
        :append-to-body="true">

      <template #default>
        <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
          <el-form-item label="资料类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择资料类型" style="width: 100%">
              <el-option label="视频" value="VIDEO"></el-option>
              <el-option label="文档" value="PDF"></el-option>
              <el-option label="图片" value="IMAGE"></el-option>
              <el-option label="其他" value="OTHER"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传资料" prop="filePath">
            <el-upload
                class="material-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :headers="uploadHeaders">
              <el-button
                  :type="formData.filePath ? 'primary' : 'default'"
                  size="small"
                  style="width: 100%; display: flex; align-items: center; justify-content: center;">
                {{ formData.filePath ? '修改文件' : '上传文件' }}
              </el-button>
              <div v-if="formData.filePath" class="upload-preview">
                <span class="file-name">{{ getFileName(formData.filePath) }}</span>
                <el-button size="small" type="text" @click="clearUploadedFile">删除</el-button>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateAndSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import { ElTable, ElTag, ElDialog, ElForm, ElFormItem, ElSelect, ElOption, ElUpload, ElButton, ElMessage, ElMessageBox, ElLink } from 'element-plus';
import { getCourseChapters, getChapterMaterials, addChapterMaterial, updateChapterMaterial, deleteChapterMaterial } from '@/api/course.js';

export default {
  components: {
    ElTable,
    ElTag,
    ElDialog,
    ElForm,
    ElFormItem,
    ElSelect,
    ElOption,
    ElUpload,
    ElButton,
    ElMessage,
    ElMessageBox,
    ElLink
  },
  setup() {
    const chapterList = ref([]);
    const selectedChapterID = ref(null);
    const materialList = ref([]);
    const dialogVisible = ref(false);
    const formData = ref({
      materialID: null,
      chapterID: null,
      type: '',
      filePath: ''
    });
    const dialogTitle = ref('新增课程资料');
    const isEditMode = ref(false);
    const formRef = ref(null);
    const uploadUrl = ref('https://jsonplaceholder.typicode.com/posts/');
    const uploadHeaders = ref({});
    const tempFile = ref(null);

    // 表单验证规则
    const formRules = {
      type: [
        { required: true, message: '请选择资料类型', trigger: 'change' }
      ],
      filePath: [
        { required: true, message: '请上传课程资料', trigger: 'change' }
      ]
    };

    // 获取章节列表（从课程管理中获取）
    const fetchChapterList = async (courseID) => {
      try {
        const res = await getCourseChapters(courseID);

        if (res.code === 1) {
          chapterList.value = res.data.chapters;
          if (res.data.chapters.length > 0) {
            selectedChapterID.value = res.data.chapters[0].chapterID;
            fetchMaterials();
          }
        } else {
          console.error('获取章节列表失败：', res.message);
          ElMessage.error(res.message || '获取章节列表失败');
        }
      } catch (error) {
        console.error('请求章节列表出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 获取章节资料
    const fetchMaterials = async () => {
      if (!selectedChapterID.value) return;

      try {
        const res = await getChapterMaterials(selectedChapterID.value);

        if (res.code === 1) {
          materialList.value = res.data.materials || [];
          formData.value.chapterID = selectedChapterID.value;
        } else {
          console.error('获取资料列表失败：', res.message);
          ElMessage.error(res.message || '获取资料列表失败');
        }
      } catch (error) {
        console.error('请求资料列表出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 打开新增资料对话框
    const openAddMaterialDialog = () => {
      if (!selectedChapterID.value) {
        ElMessage.warning('请先选择章节');
        return;
      }

      dialogTitle.value = '新增课程资料';
      isEditMode.value = false;
      formData.value = {
        chapterID: selectedChapterID.value,
        type: '',
        filePath: ''
      };
      tempFile.value = null;

      nextTick(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
      });

      dialogVisible.value = true;
    };

    // 打开编辑资料对话框
    const openEditMaterialDialog = (material) => {
      dialogTitle.value = '编辑课程资料';
      isEditMode.value = true;
      formData.value = {
        materialID: material.materialID,
        chapterID: selectedChapterID.value,
        type: material.type,
        filePath: material.filePath
      };
      tempFile.value = null;

      nextTick(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
      });

      dialogVisible.value = true;
    };

    // 对话框打开回调
    const onDialogOpen = () => {
      console.log('对话框已打开');
    };

    // 对话框关闭回调
    const onDialogClose = () => {
      tempFile.value = null;
      console.log('对话框已关闭');
    };

    // 验证并保存资料
    const validateAndSave = () => {
      if (!formRef.value) return;

      formRef.value.validate((valid) => {
        if (valid) {
          handleSaveMaterial();
        } else {
          console.error('表单验证失败');
          ElMessage.error('请填写所有必填字段');
          return false;
        }
      });
    };

    // 保存资料（新增/编辑）
    const handleSaveMaterial = async () => {
      if (!tempFile.value && !isEditMode.value) {
        ElMessage.error('新增资料时必须上传文件');
        return;
      }

      try {
        let res;
        const formDataObj = new FormData();

        formDataObj.append('type', formData.value.type);
        formDataObj.append('chapterID', formData.value.chapterID);

        if (isEditMode.value) {
          formDataObj.append('materialID', formData.value.materialID);
        }

        if (tempFile.value) {
          formDataObj.append('filePath', tempFile.value);
        }

        if (isEditMode.value) {
          // 修改资料
          res = await updateChapterMaterial(formDataObj);
        } else {
          // 新增资料
          res = await addChapterMaterial(formDataObj);
        }

        if (res && res.code === 1) {
          dialogVisible.value = false;
          fetchMaterials();
          ElMessage.success(isEditMode.value ? '资料更新成功' : '资料新增成功');
        } else {
          console.error(isEditMode.value ? '资料更新失败' : '资料新增失败：', res ? res.message : '未知错误');
          ElMessage.error(res ? res.message : (isEditMode.value ? '资料更新失败' : '资料新增失败'));
        }
      } catch (error) {
        console.error('请求出错：', error);
        ElMessage.error('网络错误，请稍后重试');
      }
    };

    // 删除资料
    const handleDeleteMaterial = (materialID) => {
      ElMessageBox.confirm(
          '确定要删除此资料吗？删除后将无法恢复。',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        try {
          const res = await deleteChapterMaterial({ materialID });

          if (res.code === 1) {
            fetchMaterials();
            ElMessage.success('资料删除成功');
          } else {
            console.error('资料删除失败：', res.message);
            ElMessage.error(res.message || '资料删除失败');
          }
        } catch (error) {
          console.error('请求出错：', error);
          ElMessage.error('网络错误，请稍后重试');
        }
      }).catch(() => {
        // 取消操作
      });
    };

    // 处理文件上传成功
    const handleUploadSuccess = (response, file) => {
      console.log('上传成功', response, file);

      const fileUrl = URL.createObjectURL(file.raw);
      formData.value.filePath = fileUrl;
      tempFile.value = file.raw;

      ElMessage.success('文件上传成功');
    };

    // 上传前处理
    const beforeUpload = (file) => {
      const isLt100M = file.size / 1024 / 1024 < 100;

      if (!isLt100M) {
        ElMessage.error('上传文件大小不能超过 100MB!');
        return false;
      }

      return true;
    };

    // 清除已上传的文件
    const clearUploadedFile = () => {
      formData.value.filePath = '';
      tempFile.value = null;
    };

    // 获取标签类型
    const getTagType = (type) => {
      const typeMap = {
        'VIDEO': 'primary',
        'PDF': 'success',
        'IMAGE': 'info',
        'OTHER': 'warning'
      };
      return typeMap[type] || 'default';
    };

    // 获取文件名
    const getFileName = (path) => {
      if (!path) return '未命名文件';
      const fileName = path.split('/').pop();
      return fileName.length > 20 ? fileName.substring(0, 20) + '...' : fileName;
    };

    // 获取章节路径（用于显示层级关系）
    const getChapterPath = (chapter) => {
      if (!chapter.parentID) return chapter.name;

      let path = chapter.name;
      let currentParentID = chapter.parentID;

      while (currentParentID) {
        const parent = findChapterById(currentParentID);
        if (parent) {
          path = parent.name + ' > ' + path;
          currentParentID = parent.parentID;
        } else {
          break;
        }
      }

      return path;
    };

    // 根据ID查找章节
    const findChapterById = (id) => {
      const flatten = (chapters) => {
        for (const chapter of chapters) {
          if (chapter.chapterID === id) return chapter;
          if (chapter.children && chapter.children.length > 0) {
            const result = flatten(chapter.children);
            if (result) return result;
          }
        }
        return null;
      };

      return flatten(chapterList.value);
    };

    // 查看文件（模拟）
    const handleViewFile = (material) => {
      ElMessage.info(`查看资料: ${getFileName(material.filePath)}`);
      // 实际应用中可以打开新窗口或下载文件
      // window.open(material.filePath);
    };

    onMounted(() => {
      // 假设先获取第一个课程的章节
      fetchChapterList(1);
    });

    return {
      chapterList,
      selectedChapterID,
      materialList,
      dialogVisible,
      formData,
      dialogTitle,
      isEditMode,
      formRef,
      formRules,
      uploadUrl,
      uploadHeaders,
      fetchChapterList,
      fetchMaterials,
      openAddMaterialDialog,
      openEditMaterialDialog,
      onDialogOpen,
      onDialogClose,
      validateAndSave,
      handleSaveMaterial,
      handleDeleteMaterial,
      handleUploadSuccess,
      beforeUpload,
      clearUploadedFile,
      getTagType,
      getFileName,
      getChapterPath,
      handleViewFile
    };
  }
};
</script>

<style scoped>
/* 样式保持与之前页面一致 */
.material-management-page {
  padding: 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.chapter-selector {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.material-list-container {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-y: auto;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.material-table {
  width: 100%;
}

.material-uploader {
  width: 100%;
}

.upload-preview {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #dcdfe6;
}

:deep(.el-upload .el-button) {
  height: 36px;
  padding: 0 20px;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-upload .el-button i) {
  margin-right: 6px;
  font-size: 14px;
}

.file-name {
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  font-size: 14px;
  color: #606266;
}

/* 深度选择器优化Element Plus按钮样式 */
.el-upload .el-button.is-primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.el-upload .el-button.is-primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-upload .el-button.is-primary:focus, .el-upload .el-button.is-primary:active {
  background-color: #3a8ee6;
  border-color: #3a8ee6;
}
</style>